"""
要求：180抽大保底，90抽小保底
10抽必出4星
90抽必出5星  抽到的时候up和常驻各占50%
P = {
  0.006                       i<=73
  0.006 + 0.06(i - 73)        74<=i<=89
  1                           i=90
}
五星中奖概率为   0.6%
四星中奖概率为   2.55%
其余的三星概率为 96.85%
"""

import random

from gacha_simulator.core.gacha_history import GachaHistory, GachaItem


class GachaSimulator:
    __up = '拾枝者'
    __five_star = [
        '贤者', '黄金', '预言家', '极恶骑', '猎月人'
    ]
    __four_star = [
        '愚者', '佩露薇利',
        '白垩', '杜林', '厄里那斯', '黄金王兽', '吞星之鲸',
        '耕地机·GN/Hu-00001', '永续谐振·SI/Ald', '进路开掘·SI/Glp', '永续永动·GL-Faf', '守望机关'
    ]
    __three_star = [
        '嗜岩·兽境猎犬', '嗜雷·兽境猎犬', '嗜岩·兽境幼兽', '嗜雷·兽境幼兽',
        '耕地机（通用型）', '重型耕地机',
        '白鹄骑士', '黑蛇骑士'
    ]

    def __init__(self, user_id: str):
        self.user_id = user_id
        self.history: dict = {}
        self.__rate_list: list[str] = []

    def wish(self, count: int) -> list[GachaItem]:
        wish_result = []
        self.__load_history()
        self.__rate_initialization()

        # 根据水位调整五星概率
        sunk_cost_ssr = self.history['sunk_cost_ssr']
        if sunk_cost_ssr > 73:
            for _ in range(sunk_cost_ssr - 73):
                self.__rate_add()

        # 开始抽卡
        for _ in range(count):
            self.history['sunk_cost_ssr'] += 1
            if self.history['sunk_cost_ssr'] > 89:
                wish_result.append(self.__gold())  # 五星保底
                continue
            if self.history['sunk_cost_ssr'] >= 74:
                self.__rate_add()

            # 抽一次
            character_rank = random.choice(self.__rate_list)
            if character_rank == 'R':
                self.history['sunk_cost_sr'] += 1
                if self.history['sunk_cost_sr'] >= 10:
                    wish_result.append(self.__purple())  # 四星保底
                    continue
                wish_result.append(self.__blue())
            elif character_rank == 'SR':
                wish_result.append(self.__purple())
            elif character_rank == 'SSR':
                wish_result.append(self.__gold())

        # 记录抽卡结果
        self.__save_history(wish_result)
        return wish_result

    @property
    def banner_character(self) -> str:
        return self.__up

    # 初始化抽卡的概率
    def __rate_initialization(self):
        self.__rate_list = []
        self.__rate_list.extend(['R' for _ in range(9685)])
        self.__rate_list.extend(['SR' for _ in range(255)])
        self.__rate_list.extend(['SSR' for _ in range(60)])
        random.shuffle(self.__rate_list)

    # 74抽之后增加概率
    def __rate_add(self):
        for _ in range(600):
            try:
                self.__rate_list.remove('R')
            except ValueError:
                return
            self.__rate_list.insert(random.randint(0, len(self.__rate_list) - 1), 'SSR')

    # 大保底还是小保底
    def __guarantees(self) -> bool:
        if self.history['is_guaranteed']:
            self.history['is_guaranteed'] = False
            return True
        res = random.choice([True, False])
        if res:
            self.history['is_guaranteed'] = False
            return True
        self.history['is_guaranteed'] = True
        return False

    # 出金了
    def __gold(self) -> GachaItem:
        self.history['sunk_cost_ssr'] = 0
        self.__rate_initialization()  # 重置出金概率
        if self.__guarantees():
            return GachaItem(self.__up, rarity=5)
        return GachaItem(random.choice(self.__five_star), rarity=5)

    def __purple(self) -> GachaItem:
        self.history['sunk_cost_sr'] = 0
        return GachaItem(random.choice(self.__four_star), rarity=4)

    def __blue(self) -> GachaItem:
        return GachaItem(random.choice(self.__three_star), rarity=3)

    def __load_history(self):
        self.history = GachaHistory.read_history(self.user_id)

    def __save_history(self, wish_items: list):
        GachaHistory.add_history(
            self.user_id,
            self.history.get('sunk_cost_ssr', 0),
            self.history.get('sunk_cost_sr', 0),
            self.history.get('is_guaranteed', False),
            wish_items
        )
